---
import { type CollectionEntry, getCollection } from "astro:content";
import Posts from "@layouts/Posts.astro";
import PostDetails from "@layouts/PostDetails.astro";
import getSortedPosts from "@utils/getSortedPosts";
import getPageNumbers from "@utils/getPageNumbers";
import slugify from "@utils/slugify";
import { SITE } from "@config";
import MotionScroll from '@components/react/UI/Progress'

import CustomText from "@components/react/custom-element/custom-text.tsx"


export interface Props {
  post: CollectionEntry<"blog">;
}

export async function getStaticPaths() {
  const posts = await getCollection("blog", () => true);

  const postResult = posts.map(post => ({
    params: { slug: slugify(post.data) },
    props: { post },
  }));

  const pagePaths = getPageNumbers(posts.length).map(pageNum => ({
    params: { slug: String(pageNum) },
  }));

  return [...postResult, ...pagePaths];
}

const { slug } = Astro.params;
const { post } = Astro.props;

const posts = await getCollection("blog");

const sortedPosts = getSortedPosts(posts);

const totalPages = getPageNumbers(sortedPosts.length);

const currentPage =
  slug && !isNaN(Number(slug)) && totalPages.includes(Number(slug))
    ? Number(slug)
    : 0;
const lastPost = currentPage * SITE.postPerPage;
const startPost = lastPost - SITE.postPerPage;

const paginatedPosts = sortedPosts.slice(startPost, lastPost);
---

{
  post ? (
    <PostDetails post={post} />
  ) : (
    <Posts
      posts={paginatedPosts}
      pageNum={currentPage}
      totalPages={totalPages.length}
    />
  )
}

<MotionScroll client:load></MotionScroll>
<!-- 没用的 -->
<CustomText client:load></CustomText>
